package wonderful.com.oneminute.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import org.lasque.tusdk.core.TuSdk;
import org.lasque.tusdk.core.seles.tusdk.FilterManager;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;

import wonderful.com.oneminute.utils.Multicomponent;
import wonderful.com.oneminute.R;

public class PhotoGraphActivity extends Activity {

    private SurfaceHolder mSurfaceholder;
    private Camera mCamera;
    private long takePhotoTime;
    private Camera.Parameters parameters;
    private SurfaceView mSurfaceView;
    private int cameraPosition = 1;//0代表前置摄像头，1代表后置摄像头

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_graph);
        // 异步方式初始化滤镜管理器
        // 需要等待滤镜管理器初始化完成，才能使用所有功能
        TuSdk.messageHub().setStatus(this, R.string.lsq_initing);
        TuSdk.checkFilterManager(mFilterManagerDelegate);
        //获取当前系统时间
        takePhotoTime = System.currentTimeMillis();
        initView();
    }

    private FilterManager.FilterManagerDelegate mFilterManagerDelegate = new FilterManager.FilterManagerDelegate() {
        @Override
        public void onFilterManagerInited(FilterManager manager) {
            TuSdk.messageHub().showSuccess(PhotoGraphActivity.this, R.string.lsq_inited);
        }
    };

    //初始化
    private void initView() {
        //初始化SurfaceView
        mSurfaceView = (SurfaceView) findViewById(R.id.photoView);
        //获取SurfaceView的Holder
        mSurfaceholder = mSurfaceView.getHolder();
        //设置类型
        mSurfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceholder.setKeepScreenOn(true);
        mSurfaceView.setFocusable(true);
        mSurfaceView.setBackgroundColor(TRIM_MEMORY_BACKGROUND);
        //添加回调接口
        mSurfaceholder.addCallback(new SurfaceHolder.Callback() {
            //surface创建时的回调方法
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (null == mCamera) {
                    //开启相机
                    mCamera = Camera.open();
                    try {
                       /* //设置相机镜头旋转90°
                        mCamera.setDisplayOrientation(90);*/
                        mCamera.setPreviewDisplay(mSurfaceholder);
                        //实现照相机的参数初始化
                        initCamera();
                        mCamera.startPreview();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            //当surface改变时的回调方法
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                //实现自动对焦
                mCamera.autoFocus(new Camera.AutoFocusCallback() {
                    @Override
                    public void onAutoFocus(boolean success, Camera camera) {
                        if (success) {
                            //实现照相机的参数初始化
                            initCamera();
                            //使自动对角生效的方法
                            camera.cancelAutoFocus();
                        }
                    }
                });
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                //停止图像显示、释放内存
                if (mCamera != null) {
                    mCamera.stopPreview();
                    mCamera.release();
                    mCamera = null;
                }
            }
        });
    }

    //相机参数的初始化设置
    private void initCamera() {
        parameters = mCamera.getParameters();
        //设置照片格式
        parameters.setPictureFormat(PixelFormat.JPEG);
        //设置照片大小
        parameters.setPictureSize(mSurfaceView.getWidth(), mSurfaceView.getHeight());
        /*//开启闪光灯
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);*/
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        //设置相机镜头显示方向
        setDisplay(parameters, mCamera);
        mCamera.setParameters(parameters);
        mCamera.startPreview();
        //实现再次对焦
        mCamera.cancelAutoFocus();
    }

    //控制图像的正确显示方向
    private void setDisplay(Camera.Parameters parameters, Camera mCamera) {
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            setDisplayOrientation(mCamera, 90);
        } else {
            parameters.setRotation(90);
        }
    }

    //实现的图像的正确显示
    private void setDisplayOrientation(Camera mCamera, int i) {
        Method downPolymorphic;
        try {
            downPolymorphic = mCamera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class});
            if (downPolymorphic != null) {
                downPolymorphic.invoke(mCamera, new Object[]{i});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void takePhoto(View view) {
        //获取当前方法的View，转化为Button
        Button mButton = (Button) view;
        //设置照片储存路径
        final String photoPath = "/sdcard/" + takePhotoTime + ".png";
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                try {
                    FileOutputStream mFileOutputStream = new FileOutputStream(new File(photoPath));
                    mFileOutputStream.write(data);
                    mFileOutputStream.close();
                    mCamera.startPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //前后摄像头切换
    public void changeCamera(View view) {
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        //获取手机摄像头个数
        cameraCount = Camera.getNumberOfCameras();
        for (int i = 0; i < cameraCount; i++) {
            //得到每一个摄像头的信息
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraPosition == 1) {
                //现在是后置，变更为前置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位
                    //停止掉原来的摄像头
                    mCamera.stopPreview();
                    //释放资源
                    mCamera.release();
                    //取消原来摄像头
                    mCamera = null;
                    //打开当前选中的摄像头
                    mCamera = Camera.open(i);
                    try {
                        //通过surfaceview显示取景
                        mCamera.setPreviewDisplay(mSurfaceholder);
                        mCamera.setDisplayOrientation(90);
                        //实现再次对焦
                        mCamera.cancelAutoFocus();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();
                    cameraPosition = 0;
                }
            } else {
                //前置， 变更为后置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    mCamera.stopPreview();
                    mCamera.release();
                    mCamera = null;
                    mCamera = Camera.open(i);
                    try {
                        //通过surfaceview显示取景
                        mCamera.setPreviewDisplay(mSurfaceholder);
                        mCamera.setDisplayOrientation(90);
                        //实现再次对焦
                        mCamera.cancelAutoFocus();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mCamera.startPreview();
                    cameraPosition = 0;
                }
            }
        }
    }

    //调用图片编辑方法
    public void editPictrue(View view) {
        new Multicomponent().showSample(this);
    }

    //退出照相界面
    public void photoClose(View view) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        }
    }
}